// import { User } from "../model/index";
const fs = require("fs");
const { promisify } = require("util");

const { User } = require("../model/index");
const { createToken } = require("../util/jwt");
const rename = promisify(fs.rename);

exports.list = async (req, res) => {
  console.log("req---user/list");

  res.json({
    user: "uer-list",
  });
};

exports.register = async (req, res) => {
  // console.log("body", req.body);
  // 校验重复
  const userModel = new User(req.body);
  const dbBack = await userModel.save();
  // res.send("user-register");
  const message = dbBack.toJSON();
  delete message.password;
  console.log(message);
  res.status(201).json(message);
};

// 用户登录
exports.login = async (req, res) => {
  console.log("body", req.body);
  const dbBack = await User.findOne(req.body);
  debugger;
  console.log('dbBack',dbBack)
  if (!dbBack) {
    res.status(402).json({ error: "邮箱或者密码不正确" });
    return
  }

  const a = dbBack.toJSON();
  a.token = await createToken(a);
  res.status(200).json(a);
};

// 上传头像
exports.headimg = async (req, res) => {
  console.log(req.file);
  var fileArr = req.file.originalname.split(".");
  var filetype = fileArr[fileArr.length - 1];
  try {
    await rename(
      './public/' + req.file.filename,
      './public/' + req.file.filename + '.' + filetype
    )
    res.status(201).json({ filepath: req.file.filename + '.' + filetype })
  } catch (error) {
    res.status(500).json({ err: error })
  }
};
